import React, { useEffect, useRef, useCallback } from 'react';
import * as echarts from 'echarts';
import '../styles/CandlestickChart.css';

const CandlestickChart = ({ data, height = 350, dates = [], showMacd = true }) => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  useEffect(() => {
    // 初始化图表
    if (chartRef.current) {
      // 如果已经有实例，先销毁
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
      
      // 创建新实例，使用深色主题
      chartInstance.current = echarts.init(chartRef.current, 'dark');
      
      // 更新图表
      updateChart();
    }
    
    // 组件卸载时销毁图表
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
    };
  }, [data, dates]);

  // 窗口大小变化时，重新调整图表大小
  useEffect(() => {
    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 更新图表数据和配置
  const updateChart = useCallback(() => {
    // 计算显示范围内的最大值、最小值和中间值
    const visibleData = data.slice(0, 30); // 假设显示最近30条数据
    let maxVal = -Infinity;
    let minVal = Infinity;
    
    visibleData.forEach(item => {
      maxVal = Math.max(maxVal, item.high);
      minVal = Math.min(minVal, item.low);
    });
    
    const midVal = (maxVal + minVal) / 2;
    if (!chartInstance.current || !data || !data.length) return;
    
    // 调试日志 - 打印前3条数据
    console.log('K线数据样例:');
    data.slice(0, 3).forEach((item, i) => {
      console.log(`第${i+1}条:`, 
        `开盘=${item.open}, 收盘=${item.close}`,
        `涨跌=${item.close > item.open ? '上涨' : '下跌'}`);
    });

    // 使用提供的日期
    const displayDates = dates.length > 0 ? dates : data.map((_, i) => `Day ${i+1}`);
    
    // 处理K线数据格式 [open, close, low, high]
    const values = data.map(item => [item.open, item.close, item.low, item.high]);
    
    // 计算MA5, MA10, MA20, MA60
    const ma5 = calculateMA(5);
    const ma10 = calculateMA(10);
    const ma20 = calculateMA(20);
    const ma60 = calculateMA(60);
    
    // 计算MACD指标
    const macdData = calculateMACD(12, 26, 9);
    
    // 获取或生成成交量数据
    const volumes = data.map(item => {
      if (item.volume) {
        return item.volume;
      } else {
        // 如果没有成交量数据，则生成模拟数据
        const priceRange = item.high - item.low;
        const baseVolume = 100000 + Math.random() * 900000; // 基础成交量
        return Math.floor(baseVolume * (1 + priceRange / 100));
      }
    });
    
    // 成交量数据，包含颜色信息
    const volumeData = data.map((item, index) => {
      const isUp = item.close > item.open; // 收盘价大于开盘价为上涨
      return {
        value: volumes[index],
        itemStyle: {
          color: isUp ? 'transparent' : '#14b143',  // 上涨空心(透明)，下跌实心绿色
          borderColor: isUp ? '#ef232a' : '#14b143', // 上涨边框红色，下跌边框绿色
          borderWidth: 2
        }
      };
    });
    
    // 图表配置
    const option = {
      backgroundColor: '#1a1a1a',
      animation: false,
      legend: {
        show: false  // 隐藏所有图例
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#333'
          },
          crossStyle: {
            color: '#555'
          }
        },
        backgroundColor: 'rgba(50,50,50,0.9)',
        borderWidth: 1,
        borderColor: '#555',
        padding: 10,
        textStyle: {
          color: '#fff'
        },
        position: function (pos, params, el, elRect, size) {
          const obj = {
            top: 10
          };
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
          return obj;
        },
        formatter: function (params) {
          if (!params || params.length === 0) return '';
          
          const param = params[0];
          const date = param.axisValue;
          const candleData = param.data;
          
          let result = `<div style="font-weight:bold;margin-bottom:3px;">${date}</div>`;
          
          if (param.seriesName === '日K') {
            // 调试日志 - 打印原始数据
            console.log('K线数据:', candleData);
            console.log('原始数据:', data[param.dataIndex]);
            
            result += `<div style="margin: 3px 0">
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#ef232a;"></span>
              开盘价: ${data[param.dataIndex].open}<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#ef232a;"></span>
              收盘价: ${data[param.dataIndex].close}<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#ef232a;"></span>
              最低价: ${data[param.dataIndex].low}<br/>
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#ef232a;"></span>
              最高价: ${data[param.dataIndex].high}<br/>
            </div>`;
          }
          
          // 移除了均线数据的显示
          
          // 显示成交量数据
          params.forEach(param => {
            if (param.seriesName === '成交量' && param.data) {
              const volumeValue = param.data.value;
              const color = param.data.itemStyle.borderColor; // 使用边框颜色
              result += `<div style="margin: 3px 0">
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>
                成交量: ${(volumeValue / 10000).toFixed(2)}万手
              </div>`;
            }
          });
          
                      // 显示MACD数据
                      if (showMacd) {
                        let difValue, deaValue, macdValue;
                        params.forEach(param => {
                          if (param.seriesName === 'DIF') difValue = param.data;
                          if (param.seriesName === 'DEA') deaValue = param.data;
                          if (param.seriesName === 'MACD') macdValue = param.data;
                        });
              
                        if (difValue !== undefined || deaValue !== undefined || macdValue !== undefined) {
                          result += `<div style="margin-top:5px;border-top:1px solid #555;padding-top:5px;font-weight:bold;">MACD(12,26,9)</div>`;
                
                          if (difValue !== undefined) {
                            result += `<div style="margin: 3px 0">
                              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#da6ee8;"></span>
                              DIF: ${difValue.toFixed(4)}
                            </div>`;
                          }
                
                          if (deaValue !== undefined) {
                            result += `<div style="margin: 3px 0">
                              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#39afe6;"></span>
                              DEA: ${deaValue.toFixed(4)}
                            </div>`;
                          }
                
                          if (macdValue !== undefined) {
                            const macdColor = macdValue >= 0 ? '#ef232a' : '#14b143';
                            result += `<div style="margin: 3px 0">
                              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${macdColor};"></span>
                              MACD: ${macdValue.toFixed(4)}
                            </div>`;
                          }
                        }
                      }
          
          return result;
        }
      },
      axisPointer: {
        link: [{ xAxisIndex: 'all' }],
        label: {
          backgroundColor: '#777'
        }
      },
      // 移除visualMap配置，使用itemStyle来控制颜色
      grid: showMacd ? [
        {
          left: '3%',
          right: '1%',  // 右侧边距从3%减小到1%
          top: '0%',
          height: '50%'
        },
        {
          left: '3%',
          right: '1%',  // 右侧边距从3%减小到1%
          top: '55%',
          height: '20%'
        },
        {
          left: '3%',
          right: '1%',  // 右侧边距从3%减小到1%
          top: '80%',
          height: '20%'
        }
      ] : [
        {
          left: '3%',
          right: '1%',  // 右侧边距从3%减小到1%
          top: '0%',
          height: '60%'
        },
        {
          left: '3%',
          right: '1%',  // 右侧边距从3%减小到1%
          top: '65%',
          height: '30%'
        }
      ],
      xAxis: showMacd ? [
        {
          type: 'category',
          data: displayDates,
          scale: true,
          boundaryGap: false,
          axisLine: { 
            onZero: false,
            lineStyle: { color: '#555' }
          },
          axisLabel: {
            color: '#ccc'
          },
          splitLine: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          axisPointer: {
            z: 100
          }
        },
        {
          type: 'category',
          gridIndex: 1,
          data: displayDates,
          scale: true,
          boundaryGap: false,
          axisLine: { 
            onZero: false,
            lineStyle: { color: '#555' }
          },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax'
        },
        {
          type: 'category',
          gridIndex: 2,
          data: displayDates,
          scale: true,
          boundaryGap: false,
          axisLine: { 
            onZero: false,
            lineStyle: { color: '#555' }
          },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: true, color: '#ccc' },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax'
        }
      ] : [
        {
          type: 'category',
          data: displayDates,
          scale: true,
          boundaryGap: false,
          axisLine: { 
            onZero: false,
            lineStyle: { color: '#555' }
          },
          axisLabel: {
            color: '#ccc'
          },
          splitLine: { show: false },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax',
          axisPointer: {
            z: 100
          }
        },
        {
          type: 'category',
          gridIndex: 1,
          data: displayDates,
          scale: true,
          boundaryGap: false,
          axisLine: { 
            onZero: false,
            lineStyle: { color: '#555' }
          },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: true, color: '#ccc' },
          splitNumber: 20,
          min: 'dataMin',
          max: 'dataMax'
        }
      ],
      yAxis: showMacd ? [
        {
          scale: true,
          position: 'left',
          z: 100,
          offset: 0,
          splitArea: { show: false },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: { color: '#888', width: 1, type: 'solid' }
          },
          axisTick: {
            show: true,
            lineStyle: { color: '#888' }
          },
          axisLabel: {
            show: true,
            inside: false,
            color: '#fff',
            backgroundColor: 'rgba(0,0,0,0.7)',
            padding: [2, 4],
            borderRadius: 2,
            formatter: function(value) {
              return value.toFixed(0);
            }
          },
          splitLine: { show: false }
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        },
        {
          scale: true,
          gridIndex: 2,
          splitNumber: 2,
          axisLabel: { 
            show: true, 
            color: '#ccc',
            formatter: function(value) {
              return value.toFixed(2);
            }
          },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        }
      ] : [
        {
          scale: true,
          position: 'left',
          z: 100,
          offset: 0,
          splitArea: { show: false },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: { color: '#888', width: 1, type: 'solid' }
          },
          axisTick: {
            show: true,
            lineStyle: { color: '#888' }
          },
          axisLabel: {
            show: true,
            inside: false,
            color: '#fff',
            backgroundColor: 'rgba(0,0,0,0.7)',
            padding: [2, 4],
            borderRadius: 2,
            formatter: function(value) {
              return value.toFixed(0);
            }
          },
          splitLine: { show: false }
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { 
            show: true, 
            color: '#ccc',
            formatter: function(value) {
              return (value / 10000).toFixed(0) + '万';
            }
          },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1],
          start: 0,
          end: 100,
          zoomOnMouseWheel: true,
          moveOnMouseMove: true
        },
        {
          show: true,
          type: 'slider',
          xAxisIndex: [0, 1],
          start: 0,
          end: 100,
          top: '97%',
          height: 20,
          borderColor: '#555',
          fillerColor: 'rgba(80,80,80,0.5)',
          textStyle: {
            color: '#ccc'
          }
        }
      ],
              series: showMacd ? [
                {
                  name: '日K',
                  type: 'candlestick',
                  data: values,
                  itemStyle: {
                    // 注意：在ECharts中，color对应收盘价<开盘价(下跌)，color0对应收盘价>开盘价(上涨)
                    color: '#14b143',    // 下跌K线：绿色实体
                    color0: '#ef232a',   // 上涨K线：红色实体 
                    borderColor: '#14b143',  // 下跌K线边框：绿色
                    borderColor0: '#ef232a'   // 上涨K线边框：红色
                  },
                  emphasis: {
                    itemStyle: {
                      color: '#14b143',    // 下跌强调状态：绿色实体
                      color0: '#ef232a',   // 上涨强调状态：红色实体
                      borderColor: '#14b143',  // 下跌强调边框：绿色
                      borderColor0: '#ef232a'   // 上涨强调边框：红色
                    }
                  }
                },
                {
                  name: 'MA5',
                  type: 'line',
                  data: calculateMA(5),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#ffffff' // 白色
                  },
                  silent: true // 不显示标签
                },
                {
                  name: 'MA10',
                  type: 'line',
                  data: calculateMA(10),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#00ffff' // 青色
                  },
                  silent: true
                },
                {
                  name: 'MA20',
                  type: 'line',
                  data: calculateMA(20),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#ff00ff' // 品红
                  },
                  silent: true
                },
                {
                  name: 'MA60',
                  type: 'line',
                  data: calculateMA(60),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#00ff00' // 绿色
                  },
                  silent: true
                },
                {
                  name: '成交量',
                  type: 'bar',
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                  data: volumeData,
                  barWidth: '60%',  // 控制柱状图宽度
                  // 不再需要在这里设置itemStyle，因为每个数据点都有自己的样式
                  emphasis: {
                    itemStyle: {
                      borderWidth: 3  // 鼠标悬停时边框加粗
                    }
                  }
                },
                // MACD指标
                {
                  name: 'MACD',
                  type: 'bar',
                  xAxisIndex: 2,
                  yAxisIndex: 2,
                  data: macdData.macd,
                  barWidth: '60%',
                  itemStyle: {
                    color: function(params) {
                      return params.data >= 0 ? '#ef232a' : '#14b143';
                    }
                  }
                },
                {
                  name: 'DIF',
                  type: 'line',
                  xAxisIndex: 2,
                  yAxisIndex: 2,
                  data: macdData.dif,
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#da6ee8' // 紫色
                  }
                },
                {
                  name: 'DEA',
                  type: 'line',
                  xAxisIndex: 2,
                  yAxisIndex: 2,
                  data: macdData.dea,
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#39afe6' // 蓝色
                  }
                }
              ] : [
                {
                  name: '日K',
                  type: 'candlestick',
                  data: values,
                  itemStyle: {
                    color0: '#14b143',  // 目前color0表示下跌K线。下跌实心绿色。是不是新版echart用于收盘价 > 开盘价（上涨K线）
                    color: 'transparent',  // 上涨空心(透明)，用于收盘价 < 开盘价（下跌K线）
                    borderColor0: '#14b143',  // 下跌边框绿色
                    borderColor: '#ef232a'  // 上涨边框红色
                  },
                  emphasis: {
                    itemStyle: {
                      color0: '#14b143',  // 下跌强调状态保持实心绿色
                      color: 'transparent',  // 上涨强调状态保持空心
                      borderColor0: '#14b143',  // 下跌边框绿色
                      borderColor: '#ef232a'  // 上涨边框红色
                    }
                  }
                },
                {
                  name: 'MA5',
                  type: 'line',
                  data: calculateMA(5),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#ffffff' // 白色
                  },
                  silent: true // 不显示标签
                },
                {
                  name: 'MA10',
                  type: 'line',
                  data: calculateMA(10),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#ffd700' // 黄色
                  },
                  silent: true
                },
                {
                  name: 'MA20',
                  type: 'line',
                  data: calculateMA(20),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#ff69b4' // 粉色
                  },
                  silent: true
                },
                {
                  name: 'MA60',
                  type: 'line',
                  data: calculateMA(60),
                  symbol: 'none',
                  lineStyle: {
                    width: 1,
                    color: '#808080' // 灰色
                  },
                  silent: true
                },
                {
                  name: '成交量',
                  type: 'bar',
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                  data: volumeData,
                  barWidth: '60%',  // 控制柱状图宽度
                  // 不再需要在这里设置itemStyle，因为每个数据点都有自己的样式
                  emphasis: {
                    itemStyle: {
                      borderWidth: 3  // 鼠标悬停时边框加粗
                    }
                  }
                }
              ]
    };

    // 设置图表配置
    chartInstance.current.setOption(option);
  };

  // 计算移动平均线
  const calculateMA = (dayCount) => {
    const result = [];
    if (!data || data.length === 0) return result;
    
    for (let i = 0; i < data.length; i++) {
      if (i < dayCount - 1) {
        result.push('-');
        continue;
      }
      let sum = 0;
      let validDays = 0;
      for (let j = 0; j < dayCount; j++) {
        if (i - j >= 0 && data[i - j] && typeof data[i - j].close === 'number') {
          sum += data[i - j].close;
          validDays++;
        }
      }
      result.push(validDays > 0 ? sum / validDays : '-');
    }
    return result;
  };

  // 计算指数移动平均线
  const calculateEMA = (period, values) => {
    const k = 2 / (period + 1);
    const emaData = [];
    let ema = values[0];
    
    for (let i = 0; i < values.length; i++) {
      if (i === 0) {
        emaData.push(ema);
      } else {
        ema = values[i] * k + ema * (1 - k);
        emaData.push(ema);
      }
    }
    return emaData;
  };

  // 计算MACD指标
  const calculateMACD = (shortPeriod, longPeriod, signalPeriod) => {
    if (!data || data.length === 0) return { dif: [], dea: [], macd: [] };

    const closeValues = data.map(item => item.close);
    
    // 计算快速和慢速EMA
    const shortEMA = calculateEMA(shortPeriod, closeValues);
    const longEMA = calculateEMA(longPeriod, closeValues);
    
    // 计算DIF (MACD线)
    const dif = shortEMA.map((value, index) => value - longEMA[index]);
    
    // 计算DEA (信号线)
    const dea = calculateEMA(signalPeriod, dif);
    
    // 计算MACD柱状图
    const macd = dif.map((value, index) => (value - dea[index]) * 2);
    
    return { dif, dea, macd };
  };

  return (
    <div className="candlestick-chart" ref={chartRef} style={{ width: '100%', height: `${height}px` }} />
  );
};

export default CandlestickChart;